package com.wrt.produce.controller;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StreamUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import com.wrt.produce.entity.Tables;
import com.wrt.produce.service.DataSourceDetailService;
import com.wrt.produce.source.DynamicDataSource;
import com.wrt.produce.util.DataBaseNameUtil;

import lombok.extern.log4j.Log4j2;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

import javax.sql.DataSource;

import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

/**
 * 数据库文档生成接口
 * 
 * @author 文瑞涛
 * @date 2021年7月13日 上午11:10:46
 */
@RestController
@Log4j2
public class DataSourceDetailController {

	@Autowired
	private DataSourceDetailService dataSourceDetailService;
	@Autowired
	private DynamicDataSource dataSource;

	@GetMapping("/produce")
	public void produce(HttpServletRequest request, HttpServletResponse response) {
		// 获取数据库名称
		String dbName = null;
		DataSource tempDataSource = dataSource.getDataSource(request.getSession().getId());
        if (null == tempDataSource) {
        	tempDataSource = dataSource.getDataSource();
        }
		try(Connection c = tempDataSource.getConnection();) {
			dbName = DataBaseNameUtil.getDataBaseNameByUrl(c.getMetaData().getURL());
		} catch (SQLException e) {
			log.error(e.getMessage(), e);
		}
		if (StringUtils.isBlank(dbName)) {
			log.error("获取数据库名称异常");
		}
		// 生成word文档
		List<Tables> list = dataSourceDetailService.getAllDataSourceName(dbName);
		
		File doc = dataSourceDetailService.toWord(dbName, list);
		
		// 将文件传给前端
		if (null != doc && doc.exists() && doc.isFile()) {
			try (ServletOutputStream out = response.getOutputStream(); FileInputStream in = new FileInputStream(doc);) {
				response.setContentType("multipart/form-data");
				response.setHeader("Content-Disposition",
						"attachment;fileName=" + URLEncoder.encode(doc.getName(), StandardCharsets.UTF_8.name()));
				response.setCharacterEncoding(StandardCharsets.UTF_8.name());
				StreamUtils.copy(in, out);
			} catch (IOException e) {
				response.reset();
				log.error(e.getMessage(), e);
			} finally {
				try {
					Files.deleteIfExists(doc.toPath());
					log.debug(doc.getAbsolutePath());
				} catch (IOException e) {
					log.error(e.getMessage(), e);
				}
			}
		} else {
			log.error("无文件");
		}
	}
}
